import time
from machine import Pin
from umqtt.simple import MQTTClient
import machine
import network, webrepl
import ubinascii
import utils

mqtt_server = 'mqtt.heclouds.com'
mqtt_port = 6002
mqtt_user = '217551'
mqtt_pwd = 'esp8266wakeup'
client_id = "518725880"
topic_sub = b'ledctl'
topic_pub = b'hello'
last_message = 0
message_interval = 5
publish_counter = 0
connect_network_retry = 12
# scan_ssid_retry = 20

unique_id = ubinascii.hexlify(machine.unique_id()).decode("utf-8")


def led_flash():
    led = Pin(2, Pin.OUT)
    led.value(0)  # on
    time.sleep(0.1)
    led.value(1)  # off


def sub_cb(topic, msg):
    led_flash()
    print((topic, msg))
    if topic == b'ledctl' and msg == b'on':
        import wakeup
        wakeup.send()
    if topic == b'ledctl' and msg == b'off':
        pass


def connect_and_subscribe():
    client = MQTTClient(client_id, mqtt_server, port=mqtt_port, user=mqtt_user, password=mqtt_pwd, keepalive=60)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(topic_sub)
    print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
    return client


def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(6)
    machine.reset()


try:
    import wifimgr

    isconnected = wifimgr.connect_to_internet()
    wlan_ap = network.WLAN(network.AP_IF)
    if isconnected:
        wlan_ap.active(False)
        webrepl.stop()
        time.sleep(3)
        client = connect_and_subscribe()
        while True:
            try:
                client.check_msg()
                if (time.time() - last_message) > message_interval:
                    msg = b'Hello #%d' % publish_counter
                    client.publish(topic_pub, msg)
                    last_message = time.time()
                    publish_counter += 1
            except OSError as e:
                restart_and_reconnect()
    # elif (store != None):
    #     import os
    #     os.remove(utils.NETWORK_PROFILES)
    #     restart_and_reconnect()

    wlan_ap.active(True)
    webrepl.start()

except OSError as e:
    print(e)
    time.sleep(30)
    restart_and_reconnect()

if __name__ == "__main__":
    pass
